import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// createRouter 创建路由实例，===> new VueRouter()
const router = createRouter({
  // 配置路由模式 当前history 
  // 如果需要使用hash模式 则引入createWebHashHistory()即可 
  // 函数 createWebHistory(import.meta.env.BASE_URL), 可以传参，默认是/
  // import.meta是javascript模块暴露描述模块的信息对象
  // env.BASE_URL是vite环境变量 来源于vite.config.ts的base选项的值默认是/
  history: createWebHistory(import.meta.env.BASE_URL),
  // 路由规则表
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    {
      path: '/user/patient', component: () => import('@/views/User/PatientPage.vue'), meta: { title: '家庭档案' }
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
      meta: { title: '极速问诊' }
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
      meta: { title: '选择科室' }
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' }
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' }
    },
    {
      path: '/room',
      component: () => import('@/views/Room/index.vue'),
      meta: { title: '问诊室' },
      beforeEnter(to) {
        if (to.query.payResult === 'false') return '/user/consult'
      }
    },
    {
      path: '/user/consult',
      component: () => import('@/views/User/ConsultPage.vue'),
      meta: { title: '问诊记录' }
    },
    {
      path: '/user/consult/:id',
      component: () => import('@/views/User/ConsultDetail.vue'),
      meta: { title: '问诊详情' }
    },

    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        { path: '/home', component: () => import('@/views/Home/index.vue'), meta: { title: '首页' } },
        { path: '/article', component: () => import('@/views/Article/index.vue'), meta: { title: '健康百科' } },
        { path: '/notify', component: () => import('@/views/Notify/index.vue'), meta: { title: '消息通知' } },
        { path: '/user', component: () => import('@/views/User/index.vue'), meta: { title: '个人中心' } }
      ]
    }
  ]

})
router.beforeEach((to) => {
  // 切换路由前开启进度条
  NProgress.start()
  // 用户仓库
  const store = useUserStore()
  // 不需要登录的页面，白名单
  const wihteList = ['/login']
  // / 如果没有登录且不在白名单内，去登录
  if (!store.user?.token && !wihteList.includes(to.path)) return '/login'
  // 否则不做任何处理
})
// 后置守卫 路由全局后置守卫设置标题给页面，扩展元信息类型
router.afterEach((to) => {
  document.title = `${to.meta.title || ''}-优医问诊`
  // 路由切换完毕后关闭
  NProgress.done()
})
NProgress.configure({
  showSpinner: false
})

export default router
